﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PServiceBus.Silverlight;

namespace SLChat {
    public partial class MainPage : UserControl {

        static readonly string UserName = "Silverlight" + Guid.NewGuid();

        public MainPage() {
            InitializeComponent();
        }

        private void SendBtn_Click(object sender, RoutedEventArgs e) {
            PSBClient.Publish(new ChatTopic { Message = InputText.Text, UserName = UserName });
            InputText.Text = string.Empty;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e) {

            PSBClient.Subscribe<ChatTopic>(msg =>
                {
                    var message = String.Format("{0}: {1}\r\n", msg.UserName, msg.Message);
                    Messages.Items.Add(message);
                    Messages.UpdateLayout();
                    Messages.ScrollIntoView(Messages.Items[Messages.Items.Count - 1]);
                    Messages.UpdateLayout();
                });

            PSBClient.Publish(new ChatTopic { Message = "add-user", UserName = UserName });
        }

        private void InputText_KeyUp(object sender, KeyEventArgs e) {
            if (e.Key == Key.Enter) SendBtn_Click(SendBtn, null);
        }
    }
    public class ChatTopic {
        public string UserName { get; set; }
        public string Message { get; set; }
    }

}
